<template>
  <div class="Detail1">
    <div class="mixin">
      <div class="right">
        <div class="search-info">
          <div class="ans">
            <div class="category-tabs">
              <div
                v-for="category in categories"
                :key="category.value"
                :class="[
                  'category-item',
                  { active: currentCategory === category.value },
                ]"
                @click="handleCategoryChange(category.value)"
              >
                {{ category.label }}
              </div>
            </div>
            <div class="search-result-area">
              <div class="operation-bar">
                <div class="left-operations">
                  <div class="operation-buttons">
                    <el-checkbox
                      class="selected-checkbox"
                      :value="isAllCurrentPageSelected"
                      @change="handleSelectAll"
                    >
                      全选
                    </el-checkbox>
                    <div class="operation-btn" @click="handleCancelCollection">
                      删除记录
                    </div>
                    <!-- <div class="operation-btn" @click="handleAnalyze">分析</div> -->
                  </div>
                </div>

                <div class="right-operations">
                  <!-- 筛选下拉菜单 -->
                  <div class="filter-container">
                    <el-dropdown @command="handleFilterChange">
                      <span class="filter-text">
                        筛选
                        <i class="el-icon-arrow-down"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="week">近一周</el-dropdown-item>
                        <el-dropdown-item command="month">近一月</el-dropdown-item>
                        <el-dropdown-item command="year">近一年</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>

                  <!-- 收藏时间排序 -->
                  <div class="sort-container" @click="toggleSortOrder">
                    <span class="sort-text">下载时间</span>
                    <i :class="sortIcon"></i>
                  </div>

                  <div class="search-controls">
                    <div class="pagination-controls" v-if="viewMode === 'fenye'">
                      <i
                        class="iconfont icon-icon-zuoyouqiehuan-zuo"
                        @click="handlePrevPage"
                        :class="{ disabled: currentPage === 1 }"
                      ></i>
                      <div class="page-info">
                        {{ currentPage }}/{{ totalPages }}
                      </div>
                      <i
                        class="iconfont icon-icon-zuoyouqiehuan-you"
                        @click="handleNextPage"
                        :class="{ disabled: currentPage === totalPages }"
                      ></i>
                    </div>
                    <div class="view-controls">
                      <div
                        class="fenye"
                        @click="handleChangeViewMode('fenye')"
                        :class="{ active: viewMode === 'fenye' }"
                      >
                        <i class="iconfont icon-fenye"></i>
                      </div>
                      <div
                        class="chanpinliebiaopubuliumoshi"
                        @click="handleChangeViewMode('chanpinliebiaopubuliumoshi')"
                        :class="{ active: viewMode === 'chanpinliebiaopubuliumoshi' }"
                      >
                        <i class="iconfont icon-chanpinliebiaopubuliumoshi"></i>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="result-list-container">
            <result-list
              :items="searchResults"
              :selected-ids="selectedIds"
              :type="types"
              @select="handleSelectItem"
              @cancel-collection="handleItemCancelCollection"
            />

            <!-- 加载状态提示 -->
            <div class="loading-tip" v-if="isLoading && viewMode === 'chanpinliebiaopubuliumoshi'">
              加载中...
            </div>
            <div class="no-more-tip" v-if="!hasMore && viewMode === 'chanpinliebiaopubuliumoshi'">
              没有更多数据了
            </div>

            <!-- 空状态 -->
            <div class="empty-state" v-if="searchResults.length === 0 && !isLoading">
              <div class="aa">
                <img src="../assets/img/wu.png" alt="空状态" />
                <div class="empty-text">暂无数据</div>
              </div>
            </div>
          </div>

          <!-- 分页组件只在分页模式下显示 -->
          <div class="pagination" v-if="viewMode === 'fenye' && searchResults.length > 0">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-size="pageSize"
              layout="prev, pager, next, jumper"
              :total="totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    <fenxi ref="feedbackDialog" ></fenxi>

    </div>
  </div>
</template>

<script>
import ResultList from "../components/SearchPage/ResultList.vue";
import fenxi from "../components/fenxi.vue";

export default {
  components: {
    ResultList,
    fenxi
  },
  data() {
    return {
      types: "我的下载",
      categories: [
        { label: "全部", value: "all" },
        { label: "报刊文章", value: "newspaper" },
        { label: "图书", value: "book" },
        { label: "研究报告", value: "report" },
        { label: "资讯动态", value: "news" },
        { label: "法规文件", value: "regulation" },
        { label: "论文", value: "thesis" },
      ],
      currentCategory: "all",
      viewMode: "fenye",
      isLoading: false,
      hasMore: true,
      allResults: [],
      currentPage: 1,
      totalCount: 0,
      pageSize: 10,
      searchResults: [],
      selectedIds: [],
      filterTime: null,
      sortOrder: null,
    };
  },
  computed: {
    totalPages() {
      if (this.totalCount === 0) return 1;
      return Math.ceil(this.totalCount / this.pageSize);
    },
    selectedCount() {
      return this.selectedIds.length;
    },
    isAllCurrentPageSelected() {
      if (this.searchResults.length === 0) return false;
      return this.searchResults.every((item) => this.selectedIds.includes(item.id));
    },
    sortIcon() {
      if (!this.sortOrder) {
        return "el-icon-sort";
      }
      return this.sortOrder === "asc" ? "el-icon-sort-asc" : "el-icon-sort-desc";
    },
  },
  methods: {
    handleScroll() {
      if (this.viewMode !== "chanpinliebiaopubuliumoshi" || !this.hasMore || this.isLoading) return;

      const container = document.querySelector(".home");
      if (!container) return;

      const { scrollTop, scrollHeight, clientHeight } = container;
      if (scrollTop + clientHeight >= scrollHeight - 50) {
        this.fetchData(true);
      }
    },
    handleCategoryChange(category) {
      if (this.currentCategory !== category) {
        this.currentCategory = category;
        this.currentPage = 1;
        this.allResults = [];
        this.selectedIds = [];
        this.hasMore = true;
        this.fetchData();
      }
    },
    handleChangeViewMode(mode) {
      if (this.viewMode === mode) return;
      
      this.viewMode = mode;
      this.currentPage = 1;
      this.allResults = [];
      this.hasMore = true;
      this.selectedIds = [];
      this.fetchData();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.selectedIds = [];
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.selectedIds = [];
      this.fetchData();
    },
    handlePrevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.selectedIds = [];
        this.fetchData();
      }
    },
    handleNextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.selectedIds = [];
        this.fetchData();
      }
    },
    handleFilterChange(timeRange) {
      this.filterTime = timeRange;
      this.currentPage = 1;
      this.allResults = [];
      this.selectedIds = [];
      this.hasMore = true;
      this.fetchData();
    },
    toggleSortOrder() {
      if (!this.sortOrder) {
        this.sortOrder = "desc";
      } else if (this.sortOrder === "desc") {
        this.sortOrder = "asc";
      } else {
        this.sortOrder = null;
      }
      this.fetchData();
    },
    handleCancelCollection() {
      if (this.selectedIds.length === 0) {
        this.$message.warning("请先选择要取消收藏的项目");
        return;
      }
      this.$confirm(
        `确定要取消选中的${this.selectedIds.length}项收藏吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.searchResults = this.searchResults.filter(
            (item) => !this.selectedIds.includes(item.id)
          );
          if (this.viewMode === "chanpinliebiaopubuliumoshi") {
            this.allResults = this.allResults.filter(
              (item) => !this.selectedIds.includes(item.id)
            );
          }
          this.selectedIds = [];
          this.totalCount -= this.selectedIds.length;
          this.$message.success("取消收藏成功");
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    handleAnalyze() {
      if (this.selectedIds.length === 0) {
        this.$message.warning("请先选择要分析的项目");
        return;
      }
      this.$message.info(`将对选中的${this.selectedIds.length}项进行分析`);
      this.$refs.feedbackDialog.openFeedbackDialog()

    },
    handleItemCancelCollection(id) {
      this.$confirm("确定要取消此项收藏吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.searchResults = this.searchResults.filter(
            (item) => item.id !== id
          );
          if (this.viewMode === "chanpinliebiaopubuliumoshi") {
            this.allResults = this.allResults.filter(
              (item) => item.id !== id
            );
          }
          this.selectedIds = this.selectedIds.filter(
            (itemId) => itemId !== id
          );
          this.totalCount--;
          this.$message.success("取消收藏成功");
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    async fetchData(isLoadMore = false) {
      if (this.isLoading) return;
      
      try {
        this.isLoading = true;
        const params = {
          page: isLoadMore ? this.currentPage + 1 : 1,
          pageSize: this.pageSize,
          category: this.currentCategory,
          filterTime: this.filterTime,
          sortOrder: this.sortOrder
        };

        // 模拟API调用
        const response = await this.mockApi(params);
        
        if (this.viewMode === "chanpinliebiaopubuliumoshi") {
          // 滚动模式：累积数据
          if (isLoadMore) {
            this.allResults = [...this.allResults, ...response.data];
            this.currentPage++;
          } else {
            this.allResults = response.data;
            this.currentPage = 1;
          }
          this.searchResults = this.allResults;
          this.hasMore = response.data.length === this.pageSize;
        } else {
          // 分页模式：替换数据
          this.searchResults = response.data;
          this.totalCount = response.total;
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        this.searchResults = [];
        this.totalCount = 0;
      } finally {
        this.isLoading = false;
      }
    },
    mockApi(params) {
      return new Promise((resolve) => {
        setTimeout(() => {
          let mockResults = Array.from({ length: params.pageSize }, (_, i) => {
            const id = (params.page - 1) * params.pageSize + i + 1;
            let source = "";
            switch (params.category) {
              case "newspaper":
                source = `报刊${Math.floor(Math.random() * 3) + 1}`;
                break;
              case "book":
                source = `出版社${Math.floor(Math.random() * 3) + 1}`;
                break;
              case "report":
                source = `研究机构${Math.floor(Math.random() * 3) + 1}`;
                break;
              case "news":
                source = `新闻网站${Math.floor(Math.random() * 3) + 1}`;
                break;
              case "regulation":
                source = `政府部门${Math.floor(Math.random() * 3) + 1}`;
                break;
              case "thesis":
                source = `高校${Math.floor(Math.random() * 3) + 1}`;
                break;
              default:
                source = `来源${Math.floor(Math.random() * 5) + 1}`;
            }

            let date;
            if (params.filterTime === "week") {
              const days = Math.floor(Math.random() * 7);
              date = new Date();
              date.setDate(date.getDate() - days);
            } else if (params.filterTime === "month") {
              const days = Math.floor(Math.random() * 30);
              date = new Date();
              date.setDate(date.getDate() - days);
            } else if (params.filterTime === "year") {
              const days = Math.floor(Math.random() * 365);
              date = new Date();
              date.setDate(date.getDate() - days);
            } else {
              date = new Date(
                2021,
                Math.floor(Math.random() * 4),
                Math.floor(Math.random() * 28) + 1
              );
            }

            const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1)
              .toString()
              .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;

            return {
              id,
              title: `${this.getCategoryLabel()} 搜索结果标题 ${id}`,
              content: `这是${this.getCategoryLabel()}搜索结果${id}的详细描述内容`,
              source,
              time: formattedDate,
              collectTimestamp: date.getTime(),
            };
          });

          if (params.sortOrder) {
            mockResults.sort((a, b) => {
              if (params.sortOrder === "asc") {
                return a.collectTimestamp - b.collectTimestamp;
              } else {
                return b.collectTimestamp - a.collectTimestamp;
              }
            });
          }

          const total = params.category === "all" 
            ? Math.floor(Math.random() * 100) + 100
            : Math.floor(Math.random() * 50) + 30;

          resolve({
            data: mockResults,
            total: total
          });
        }, 300);
      });
    },
    getCategoryLabel() {
      const category = this.categories.find(
        (c) => c.value === this.currentCategory
      );
      return category ? category.label : "";
    },
    handleSelectAll(val) {
      if (val) {
        const currentUnselectedIds = this.searchResults
          .map((item) => item.id)
          .filter((id) => !this.selectedIds.includes(id));
        this.selectedIds = [
          ...new Set([...this.selectedIds, ...currentUnselectedIds]),
        ];
      } else {
        const currentPageIds = this.searchResults.map((item) => item.id);
        this.selectedIds = this.selectedIds.filter(
          (id) => !currentPageIds.includes(id)
        );
      }
    },
    handleClearSelection() {
      this.selectedIds = [];
    },
    handleSelectItem(checked, id) {
      if (checked) {
        if (!this.selectedIds.includes(id)) {
          this.selectedIds.push(id);
        }
      } else {
        this.selectedIds = this.selectedIds.filter(
          (itemId) => itemId !== id
        );
      }
    },
  },
  mounted() {
    const container = document.querySelector(".home");
    if (container) {
      container.addEventListener("scroll", this.handleScroll);
    }
  },
  created() {
    this.fetchData();
  },
  beforeDestroy() {
    const container = document.querySelector(".home");
    if (container) {
      container.removeEventListener("scroll", this.handleScroll);
    }
  },
};
</script>

<style lang="scss" scoped>
.ans {
  width: 1060px;
  height: 164px;
  background: #ffffff;
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.07);
  border-radius: 4px;
  margin-bottom: 20px;

  .category-tabs {
    display: flex;
    padding: 0 22px;
    padding-bottom: 27px;
    border-bottom: 1px solid #e4e4e4;

    .category-item {
      padding-top: 20px;
      margin-right: 54px;
      cursor: pointer;
      position: relative;
      transition: all 0.3s ease;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 20px;
      color: #999999;

      &:hover {
        color: #327dff;
      }

      &.active {
        color: #327dff;
        font-weight: 500;

        &::after {
          content: "";
          position: absolute;
          bottom: -11px;
          left: 0;
          width: 100%;
          height: 4px;
          background: #327dff;
          border-radius: 2px;
        }
      }
    }
  }

  .search-result-area {
    margin-bottom: 20px;

    .operation-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30px 20px;

      .left-operations {
        .operation-buttons {
          display: flex;
          align-items: center;

          .selected-checkbox {
            margin-right: 20px;

            ::v-deep .el-checkbox__label {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 18px;
              color: #333333;
            }
          }

          .operation-btn {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 18px;
            color: #333333;
            margin-right: 20px;
            cursor: pointer;

            &:hover {
              color: #327dff;
            }
          }
        }
      }

      .right-operations {
        display: flex;
        align-items: center;

        .filter-container {
          margin-right: 20px;

          .filter-text {
            font-size: 18px;
            color: #333;
            cursor: pointer;
            display: inline-flex;
            align-items: center;

            i {
              margin-left: 5px;
              font-size: 14px;
            }
          }
        }

        .sort-container {
          margin-right: 20px;
          cursor: pointer;

          .sort-text {
            font-size: 18px;
            color: #333;
          }

          i {
            margin-left: 5px;
            font-size: 14px;
          }
        }
      }
    }
  }

  .search-controls {
    display: flex;

    .pagination-controls {
      display: flex;
      align-items: center;
      font-size: 18px;
      color: #333;

      .page-info {
        padding: 0 17px;
      }

      i {
        cursor: pointer;

        &.disabled {
          cursor: not-allowed;
          color: #ccc;
        }
      }
    }

    .view-controls {
      display: flex;
      align-items: center;
      height: 28px;
      background: #fff;
      border-radius: 2px;
      border: 1px solid #e4e4e4;
      margin-left: 16px;

      .chanpinliebiaopubuliumoshi,
      .fenye {
        cursor: pointer;
        width: 36px;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        &.active {
          color: #327dff;
        }
      }

      .fenye {
        border-right: 1px solid #e4e4e4;

        i {
          font-size: 16px;
        }
      }

      .chanpinliebiaopubuliumoshi {
        i {
          font-size: 19px;
        }
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: flex-end;
}

.loading-tip, .no-more-tip {
  text-align: center;
  padding: 20px 0;
  color: #666;
  font-size: 14px;
}

.no-more-tip {
  color: #999;
}

::v-deep .el-pager li {
  background-color: #f9faff;
}

::v-deep .el-pagination .btn-next,
.el-pagination .btn-prev {
  background-color: #f9faff;
}

::v-deep .el-dropdown-menu {
  min-width: 100px;
}

.search-info {
  width: 1060px;
}

.result-list-container {
  width: 1060px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 160px 0;
  color: #999;

  .aa {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #666666;

    .empty-text {
      margin-top: 18px;
    }
  }
}
</style>
